package data_structure.mooc;

import data_structure.implement.QueueImp;

public class LinkedListQueue<E> implements QueueImp<E> {

    private class Node {
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this (e, null);
        }

        public Node() {
            this (null, null);
        }

        @Override
        public String toString() {
            return e.toString ();
        }
    }
    private Node head,tail;
    private int size;

    public LinkedListQueue() {
        head=null;
        tail=null;
        size=0;
    }



    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public void enqueue(E e) {
        if(tail==null){
            tail=new Node(e);
            head=tail;
        } else{
          tail.next=new Node(e);
          tail=tail.next;
        }
        size++;
    }

    @Override
    public E dequeue() {
        if(isEmpty ()){
            throw new IllegalArgumentException ("Dequeue failed,the queue is empty");
        }
        Node temp=head;
        head=head.next;
        temp.next = null;
        //maintain variable tail manually
        //head==null---->tail=null
        if(head==null){
            tail=null;
        }
        size++;
        return temp.e;
    }

    @Override
    public E getFront() {
        return null;
    }

    @Override
    public int getSize() {
        return size;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("List:");
        Node current=head;
        sb.append ("queue: front ");
        while (current != null) {
            sb.append (current.e).append ("-->");
            current=current.next;
        }
        sb.append("NULL tail");
        return sb.toString ();
    }

}
